<template>
  <el-dialog :title="$t('tool.modelManage.' + title)" :visible.sync="dialogFormVisible" custom-class="jtyj-dialog"
    :close-on-click-modal="false">
    <el-form ref="form" :model="form" :rules="rules" label-position="top">
      <el-form-item :label="$t('tool.modelManage.chineseName')" :prop="getCurrentFormValue('name')">
        <el-input v-model="form[getCurrentFormValue('name')]" autocomplete="off" class="jtyj-input"
          :placeholder="$t('tool.others.placehoderInput')"></el-input>
      </el-form-item>
      <el-form-item v-if="flag != 'model'" :label="$t('tool.modelManage.englishName')"
        :prop="getCurrentFormValue('englishName')">
        <el-input v-model="form[getCurrentFormValue('englishName')]" autocomplete="off" class="jtyj-input"
          :placeholder="$t('tool.others.placehoderInput')"></el-input>
      </el-form-item>
      <el-form-item v-if="flag != 'model'" :label="$t('tool.modelManage.folderDescription')"
        :prop="getCurrentFormValue('description')">
        <el-input v-model="form[getCurrentFormValue('description')]" autocomplete="off" class="jtyj-input"
          :placeholder="$t('tool.others.placehoderInput')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('tool.modelManage.parentFolder')">
        <treeselect v-model="form.parentId" :options="treeData" class="jtyj-input" :disabled="flag == 'dataModeling'">
        </treeselect>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button class="jtyj-btn-cancel" @click="cancel">{{
        $t("setup.buttonText.cancel")
      }}</el-button>
      <el-button class="jtyj-btn-primary" @click="submitForm">{{
        $t("setup.buttonText.save")
      }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  addModel,
  addGlobalData,
  updateModel,
  updateGlobalData,
  addModelFolder,
  updateModelFolder,
  addModelData,
  updateModelData,
} from "@/api/myspace/model-manage-tool/model-manage";
import { mapState } from "vuex";
export default {
  data() {
    return {
      title: "",
      flag: "", // 新增文件夹的标志，判断是哪个部分的新增
      dialogFormVisible: false,
      form: {
        modelName: null,
        modelEnglishName: null,
        modelDescription: null,
        globalDataName: null,
        fileName: null,
        modelDataName: null,
        parentId: 0,
        userId: null,
        nodeType: 0,
        modelId: null,
        mainVersion: null,
        modelDataType: null,
        globalDataType: null,
        fileId: null,
        fileDataName: null,
        modelDataId: null,
        globalDataId: null,
      },
      treeData: [],
      rules: {
        modelEnglishName: [{ required: true, message: "请输入英文名称", trigger: "blur" }],
        globalEnglishName: [{ required: true, message: "请输入英文名称", trigger: "blur" }],
      },
    };
  },
  computed: {
    ...mapState({
      userId: (state) => state.user.id,
    }),
  },
  methods: {
    init(sign, node, treeData, flag, modelId, mainVersionId) {
      this.dialogFormVisible = true;
      this.flag = flag;
      this.reset(treeData, modelId, mainVersionId);
      if (sign == "add") {
        this.title = "newFolder";
        if (node) {
          // 新增子目录
          this.form.parentId = node.id;
          this.form.modelDataType = node.data.modelDataType;
          this.form.globalDataType = node.data.globalDataType;
        }
      } else {
        this.title = "addFolder";
        this.form.parentId = node.parentId;

        if (flag == "account") {
          this.form.modelId = node.id;
          this.form.modelName = node.name;
          this.form.modelEnglishName = node.data.modelEnglishName;
          this.form.modelDescription = node.data.modelDescription;
        } else if (flag == "model") {
          this.form.fileId = node.id;
          this.form.fileName = node.name;
        } else if (flag == "dataModeling") {
          this.form.modelDataId = node.id;
          this.form.modelDataName = node.name;
          this.form.dataEnglishName = node.data.dataEnglishName;
          this.form.modelDataType = node.data.modelDataType;
          this.form.modelDataDescription = node.data.modelDataDescription;
        } else if (flag == "global") {
          this.form.globalDataId = node.id;
          this.form.globalDataName = node.name;
          this.form.globalEnglishName = node.data.globalEnglishName;
          this.form.globalDataType = node.data.globalDataType;
          this.form.globalDataDescription = node.data.globalDataDescription;
        }
      }
    },
    // 获取当前表单绑定的数据
    getCurrentFormValue(param) {
      if (this.flag == "account") {
        switch (param) {
          case "name":
            return "modelName";
          case "description":
            return "modelDescription";
          case "englishName":
            return "modelEnglishName";
        }
      } else if (this.flag == "dataModeling") {
        switch (param) {
          case "name":
            return "modelDataName";
          case "description":
            return "modelDataDescription";
          case "englishName":
            return "dataEnglishName";
        }
      } else if (this.flag == "global") {
        switch (param) {
          case "name":
            return "globalDataName";
          case "description":
            return "globalDataDescription";
          case "englishName":
            return "globalEnglishName";
        }
      } else if (this.flag == "model") {
        switch (param) {
          case "name":
            return "fileName";
          case "description":
            return "globalDataDescription";
          case "englishName":
            return "fileEnglishName";
        }
      }
      return ""; // 默认返回空字符串，避免未定义属性
    },
    // 将树结构数据格式化为需要的结构
    filterTreeByType(tree, type) {
      // 定义递归函数来筛选子节点
      function filterChildren(children, parentId) {
        if (!children || children.length === 0) return [];

        // 筛选出符合条件的子节点
        const filteredChildren = children
          .filter((child) => child.type === type)
          .map((child) => {
            // 递归处理子节点
            const filteredChild = {
              id: child.id,
              label: child.name,
              children: [],
              parentId: parentId,
            };
            filteredChild.children = filterChildren(child.children, child.id);
            if (filteredChild.children.length == 0) {
              delete filteredChild.children;
            }
            return filteredChild;
          });

        return filteredChildren;
      }

      // 筛选根节点
      const filteredTree = tree
        .filter((node) => node.type === type)
        .map((node) => {
          const filteredNode = {
            id: node.id,
            label: node.name,
            children: [],
            parentId: 0,
          };
          filteredNode.children = filterChildren(node.children, node.id);
          if (filteredNode.children.length == 0) {
            delete filteredNode.children;
          }
          return filteredNode;
        });

      return filteredTree;
    },
    reset(treeData, modelId, mainVersionId) {
      if (this.flag == "dataModeling") {
        this.treeData = this.filterTreeByType(treeData, 0);
      } else {
        this.treeData = [];
        const menu = {
          id: 0,
          label: "根目录",
          children: [],
          parentId: -1,
        };
        menu.children = this.filterTreeByType(treeData, 0);
        this.treeData.push(menu);
      }

      this.form =
        this.flag == "account"
          ? {
            modelId: null,
            modelName: null,
            modelEnglishName: null,
            modelDescription: null,
            parentId: 0,
            userId: null,
            nodeType: 0, // 0表示文件夹，1表示文件
          }
          : this.flag == "model"
            ? {
              fileId: null,
              fileName: null,
              parentId: 0,
              userId: null,
              nodeType: 0,
            }
            : this.flag == "global"
              ? {
                globalDataId: null,
                globalDataName: null,
                parentId: 0,
                userId: null,
                nodeType: 0,
                globalDataType: null
              } : {
                modelDataId: null,
                modelDataName: null,
                parentId: 0,
                userId: null,
                nodeType: 0,
                modelId: modelId,
                mainVersion: mainVersionId,
                modelDataType: null,
              };
      this.resetForm("form");
    },
    cancel() {
      this.dialogFormVisible = false;
    },
    // 表单提交
    submitForm() {
      this.form.userId = this.userId;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.flag == "account") {
            if (this.form.modelId == null) {
              addModel(this.form).then((response) => {
                if (response.code == 200) {
                  this.$message.success(
                    this.$toolHandle.getI18nName(
                      this.$zh.setup.responseText,
                      this.$en.setup.responseText,
                      this.$i18n.locale,
                      "success"
                    )
                  );
                  this.$emit("refresh");
                  this.dialogFormVisible = false;
                }
              });
            } else {
              updateModel(this.form).then((response) => {
                if (response.code == 200) {
                  this.$message.success(
                    this.$toolHandle.getI18nName(
                      this.$zh.setup.responseText,
                      this.$en.setup.responseText,
                      this.$i18n.locale,
                      "success"
                    )
                  );
                  this.$emit("refresh");
                  this.dialogFormVisible = false;
                }
              });
            }
          } else if (this.flag == "model") {
            if (this.form.fileId == null) {
              addModelFolder(this.form).then((response) => {
                if (response.code == 200) {
                  this.$message.success(
                    this.$toolHandle.getI18nName(
                      this.$zh.setup.responseText,
                      this.$en.setup.responseText,
                      this.$i18n.locale,
                      "success"
                    )
                  );
                  this.$emit("refresh");
                  this.dialogFormVisible = false;
                }
              });
            } else {
              updateModelFolder(this.form).then((response) => {
                if (response.code == 200) {
                  this.$message.success(
                    this.$toolHandle.getI18nName(
                      this.$zh.setup.responseText,
                      this.$en.setup.responseText,
                      this.$i18n.locale,
                      "success"
                    )
                  );
                  this.$emit("refresh");
                  this.dialogFormVisible = false;
                }
              });
            }
          } else if (this.flag == "dataModeling") {
            if (this.form.modelDataId == null) {
              addModelData(this.form).then((response) => {
                if (response.code == 200) {
                  this.$message.success(
                    this.$toolHandle.getI18nName(
                      this.$zh.setup.responseText,
                      this.$en.setup.responseText,
                      this.$i18n.locale,
                      "success"
                    )
                  );
                  this.$emit("refresh");
                  this.dialogFormVisible = false;
                }
              });
            } else {
              updateModelData(this.form).then((response) => {
                if (response.code == 200) {
                  this.$message.success(
                    this.$toolHandle.getI18nName(
                      this.$zh.setup.responseText,
                      this.$en.setup.responseText,
                      this.$i18n.locale,
                      "success"
                    )
                  );
                  this.$emit("refresh");
                  this.dialogFormVisible = false;
                }
              });
            }
          } else if (this.flag == "global") {
            if (this.form.globalDataId == null) {
              addGlobalData(this.form).then((response) => {
                if (response.code == 200) {
                  this.$message.success(
                    this.$toolHandle.getI18nName(
                      this.$zh.setup.responseText,
                      this.$en.setup.responseText,
                      this.$i18n.locale,
                      "success"
                    )
                  );
                  this.$emit("refresh");
                  this.dialogFormVisible = false;
                }
              });
            } else {
              updateGlobalData(this.form).then((response) => {
                if (response.code == 200) {
                  this.$message.success(
                    this.$toolHandle.getI18nName(
                      this.$zh.setup.responseText,
                      this.$en.setup.responseText,
                      this.$i18n.locale,
                      "success"
                    )
                  );
                  this.$emit("refresh");
                  this.dialogFormVisible = false;
                }
              });
            }
          }
        }
      });
    },
  },
};
</script>

<style></style>